package com.spring.security.dao;

import com.google.common.collect.Lists;
import com.spring.security.entity.SysRole;
import com.spring.security.entity.SysUser;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * ClassName: SysUserRepositoryImpl
 * Desc:
 * Date： 2017/5/26
 * Created：shaom
 */
@Repository
public class SysUserRepositoryImpl implements SysUserRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public SysUser findByUsername(String username) {
        String sql = "select a.id aid, a.username, a.password, c.id cid, c.name from sys_user a, sys_user_roles b, sys_role c where" +
                "  a.id = b.sys_user_id AND b.roles_id = c.id AND username = '"+ username +"'";

        SysUser sysUser = jdbcTemplate.queryForObject(sql, new RowMapper<SysUser>() {
            @Override
            public SysUser mapRow(ResultSet rs, int rowNum) throws SQLException {
                SysUser sysUser1 = new SysUser();
                sysUser1.setId(rs.getLong("aid"));
                sysUser1.setUsername(rs.getString("username"));
                sysUser1.setPassword(rs.getString("password"));

                SysRole role = new SysRole();
                role.setId(rs.getLong("cid"));
                role.setName(rs.getString("name"));
                sysUser1.setRoles(Lists.newArrayList(role));

                return sysUser1;
            }
        });
        return sysUser;
    }
}
